<template>
  <div>
    <div class="query-form">
      <el-checkbox v-model="enableValid" style="margin-top: 10px;" @change="_getMenuList">查看禁用菜单</el-checkbox>
      <div class="right-btns">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddMenu(null)">添加模块</el-button>
      </div>
    </div>

    <el-table
      :data="menuList"
      border
      row-key="id"
      :tree-props="{children: 'children'}"
      v-loading="queryLoading">
    >
      <el-table-column
        fixed
        prop="name"
        label="菜单名称"
        width="140"
      >
        <template slot-scope="scope">
          <i v-if="(scope.row.pid === '0') && (scope.row.children.length === 0)" class="el-icon-notebook-2" style="padding: 0 10px;"/>
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column
        prop="icon"
        label="菜单图标"
        width="180"
      >
        <template slot-scope="scope">
          <i :class="scope.row.icon" class="color-success" style="font-size: 16px; margin-right: 6px;"/>
          {{scope.row.icon}}
        </template>
      </el-table-column>
      <el-table-column
        prop="sort"
        label="菜单排序"
        width="80"
      >
      </el-table-column>
      <el-table-column
        prop="url"
        label="URl"
        min-width="140"
      >
      </el-table-column>
      <el-table-column
        prop="desc"
        label="描述"
        min-width="200"
      >
      </el-table-column>
      <el-table-column
        prop="valid"
        label="状态"
        width="100"
        align="center"
      >
        <el-switch slot-scope="scope" class="el-switch-cutomer" :value="scope.row.valid" :width="62" size="mini" :active-value="1" :inactive-value="0" @click.native="handleToggleValid(scope.row)"></el-switch>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="140"
        align="center"
      >
        <template slot-scope="scope">
          <el-button v-if="scope.row.pid === '0'" type="text" @click="handleAddMenu(scope.row.id)">增加子菜单</el-button>
          <el-button type="text" @click="handleEditMenu(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表单区域 -->
    <el-dialog
      :title="menuForm.id ? '修改菜单' : '新增菜单'"
      :visible.sync="showMenuForm"
      :close-on-click-modal="false"
      width="520px">
      <el-form :model="menuForm" ref="menuForm" :rules="rules" label-width="80px" style="margin: 0 auto;">
        <el-form-item label="名称" prop="name">
          <el-input v-model="menuForm.name" autocomplete="off" style="width:300px" placeholder="请输入菜单名称"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-select v-model="menuForm.icon" filterable clearable autocomplete="off" placeholder="请选择或输入图标" style="width:300px" >
            <el-option
              v-for="item in iconOptions"
              :key="item"
              :label="item"
              :value="item">
              <i :class="item"/>&nbsp;&nbsp;&nbsp;{{ item }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="menuForm.sort" :min="-1000" :max="1000" ></el-input-number>
        </el-form-item>
        <el-form-item label="URL" prop="url">
          <el-input v-model="menuForm.url" autocomplete="off" style="width:300px" placeholder="请输入URL"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input type="textarea"  :rows="3" maxlength="200" show-word-limit v-model="menuForm.desc" autocomplete="off" style="width:300px" placeholder="请输入菜单描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showMenuForm = false">取&nbsp;消</el-button>
        <el-button type="primary" @click="handleSubmitForm" :loading="submitLoading">提&nbsp;交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getTrees } from '../../utils/tree'

export default {
  name: 'MenuList',
  data() {
    return {
      queryLoading: false,
      submitLoading: false,
      showMenuForm: false,
      enableValid: false,
      menuList: [],
      iconOptions: require('./icon'),
      menuForm: {
        id: null,
        pid: '0',
        name: '',
        icon: '',
        sort: 0,
        url: '',
        desc: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { type: 'string', max: 20, message: '长度不能超过20个字', trigger: 'blur' }
        ],
        url: { pattern: /^((\/?\w+)+)$/, message: '请输入正确格式的URL，示例：/xx/xx/xx...', trigger: 'blur' }
      }
    }
  },
  created() {
    this._getMenuList()
  },
  methods: {
    _getMenuList() {
      this.queryLoading = true
      const params = {}
      if (!this.enableValid) {
        params.valid = 1
      }
      this.$http.get('/api/Menu/getMenuList', params).then(res => {
        this.menuList = getTrees(res.data, '0')
      }).finally(() => {
        this.queryLoading = false
      })
    },
    formateData(data) {
      for (const key in this.menuForm) {
        if (data.hasOwnProperty(key) && data[key]) {
          this.menuForm[key] = data[key]
        }
      }
    },
    handleAddMenu(rowId) {
      this.$refs.menuForm && this.$refs.menuForm.clearValidate()

      this.menuForm = {
        id: null,
        pid: rowId || '0',
        name: '',
        icon: '',
        sort: 0,
        url: '',
        desc: ''
      }
      this.showMenuForm = true
    },
    handleEditMenu(row) {
      for (const key in this.menuForm) {
        if (row.hasOwnProperty(key) && row[key]) {
          this.menuForm[key] = row[key]
        }
      }
      this.showMenuForm = true
    },
    handleToggleValid(row) {
      this.$confirm(`确定${row.valid ? '禁用' : '启用'}菜单【${row.name}】`, '提示').then(() => {
        this.$http.put(`/api/Menu/updateValid/${row.id}?valid=${row.valid ? 0 : 1}`).then(() => {
          this.$message.success((row.valid ? '禁用' : '启用') + '菜单成功！')
          row.valid = row.valid ? 0 : 1
        })
      })
    },
    handleSubmitForm() {
      this.$refs.menuForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          const params = Object.assign({}, this.menuForm)
          if (params.id) {
            // 修改
            this.$http.put('/api/Menu/updateMenu', params).then(() => {
              this.$message.success('修改菜单成功！')
              this._getMenuList()
              this.showMenuForm = false
            }).finally(() => {
              this.submitLoading = false
            })
          } else {
            // 增加
            this.$http.post('/api/Menu/addMenu', params).then(() => {
              this.$message.success('添加菜单成功！')
              this._getMenuList()
              this.showMenuForm = false
            }).finally(() => {
              this.submitLoading = false
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
.menu-wrapper
  padding 15px
  border-radius 3px
  background #fff
</style>